package com.schoolcloud.api.config;

import com.schoolcloud.common.exception.ServiceException;
import com.schoolcloud.common.model.R;
import feign.FeignException;
import feign.Response;
import feign.codec.DecodeException;
import feign.codec.Decoder;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.ResponseEntityDecoder;
import org.springframework.cloud.openfeign.support.SpringDecoder;

import java.io.IOException;
import java.lang.reflect.Type;

/**feign响应拦截器
 * @author hongmizfb
 * @date 2025/03/03
 */
public class FeignResponseInterceptor implements Decoder {

    private final Decoder delegate;

    public FeignResponseInterceptor() {
        ObjectFactory<HttpMessageConverters> messageConverters = HttpMessageConverters::new;
        this.delegate = new ResponseEntityDecoder(new SpringDecoder(messageConverters));
    }

    @Override
    public Object decode(Response response, Type type) throws IOException, DecodeException, FeignException {
        Object result = delegate.decode(response, type);
        if (result instanceof R<?> r) {
            if (r.getCode() != 200) {
                throw new ServiceException(r.getCode(), r.getMsg());
            }
        }
        return result;
    }
}
